package com.xinyue.design.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * 容器节点
 */
public class Composite extends Component{

	private List<Component> childComponents = null;
	
	/**
	 * 通常在里面需要实现递归的调用
	 */
	@Override
	public void tryOn() {
		if(childComponents != null) {
			for (Component cm : childComponents) {
				cm.tryOn();
			}
		}
	}

	@Override
	public void addChild(Component child) {
		//延迟初始化
		if (childComponents == null) {
			childComponents = new ArrayList<Component>();
		}
		childComponents.add(child);
	}

	@Override
	public void removeChild(Component child) {
		if (childComponents != null) {
			childComponents.remove(child);
		}
	}

	@Override
	public Component getChildren(int index) {
		 if (childComponents != null){
			 if(index >= 0 && index < childComponents.size()){
				 return childComponents.get(index);
			 }
		 }
		return null;
	}
}
